package com.util.seo;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

public class TextUtil {
	private static VelocityEngine velocityEngine = null;

	private static synchronized VelocityEngine getVelocityEngine() {
		if (velocityEngine == null) {
			velocityEngine = new VelocityEngine();
			// velocityEngine.setProperty("file.resource.loader.path",
			// "D:/workspace/web/WebRoot/");
			velocityEngine.setProperty("file.resource.loader.path", "D:/workspace/shop/WebRoot/");
			try {
				velocityEngine.init();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return velocityEngine;
	}

	/**
	 * 
	 * @param vc
	 * @param vmFile
	 *            模板名（相对于 Constant.APP_ROOT的路径）
	 * @param toFile
	 *            要写入的文件（绝对路径）
	 * @param encoding
	 */
	public static void write2File(VelocityContext vc, String vmFile, String toFile, String encoding) {
		Writer fsw = null;
		try {
			File pathFile = new File(toFile).getParentFile();
			if (!pathFile.exists()) {
				pathFile.mkdirs();
			}
			Template template = getVelocityEngine().getTemplate(vmFile, encoding);
			fsw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(toFile), encoding));
			template.merge(vc, fsw);
		} catch (ResourceNotFoundException e) {
			e.printStackTrace();
		} catch (ParseErrorException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fsw != null) {
				try {
					fsw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static void main(String[] args) {
		System.out.println("");
		VelocityContext vc = new VelocityContext();
		vc.put("asdf", "一二三");
		write2File(vc, "/WEB-INF/pages/vm/cantingContent.vm", "c:/temp/coupon.html", "GBK");
		System.out.println("over");
	}
}
